using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;

namespace com.savage.mmtoxbmcexporter
{
    class FTPUtils
    {
        private string m_IPAddress;
        private string m_username;
        private string m_password;
        private NetworkCredential m_credentials;
        public FTPUtils(string ipAddress, string username, string password)
        {
            m_IPAddress = ipAddress;
            m_username = username;
            m_password = password;
            m_credentials = new NetworkCredential(m_username, m_password);
        }

        private string CreateURL(string folderName)
        {
            string url = folderName;
            if (StartsWithDriveLetter(folderName))
            {
                url = "/" + folderName.Substring(0, 1) + fixBackslashes(folderName.Substring(2));
            }
            if (!url.StartsWith("/"))
            {
                throw new Exception("Error: folder name must be absolute path");
            }
            url = "ftp://" + m_IPAddress + url;
            return url;
        }

        private bool StartsWithDriveLetter(string folderName)
        {
            for (int letter = 'a'; letter <= 'z'; letter++)
            {
                string driveName = new string((char)letter, 1) + ":\\";
                if (folderName.ToLower().StartsWith(driveName))
                {
                    return true;
                }
            }
            return false;
        }

        private string CombineURL(string baseURL, string fileOrFolderName)
        {
            if (!baseURL.EndsWith("/"))
            {
                baseURL += "/";
            }
            return baseURL + fileOrFolderName;
        }

        private string fixBackslashes(string path)
        {
            return path.Replace("\\", "/");
        }

        public void UploadFile(string filePath, string destinationFolder)
        {
            WebClient request = new WebClient();
            request.Credentials = new NetworkCredential(m_username, m_password);

            try
            {
                string url = CombineURL(CreateURL(destinationFolder), Path.GetFileName(filePath));
                byte[] responseData = request.UploadFile(url, filePath);
                string responseString = System.Text.Encoding.UTF8.GetString(responseData);
                Console.WriteLine(responseString);
            }
            catch (WebException e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {
                request.Dispose();
            }
        }
        public void ClearDirectory(string folderName)
        {
            string url = CreateURL(folderName);
            RecursiveClearDirectory(url);
        }

        private void RecursiveClearDirectory(string url)
        {
            // get dir listing
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
            request.Credentials = m_credentials;
            request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            Stream responseStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(responseStream);
            List<string> files = new List<string>();
            List<string> directories = new List<string>();
            string anItem = reader.ReadLine();
            while (anItem != null)
            {
                string itemName = anItem.Substring(55);
                if (anItem[0] == 'd')
                {
                    directories.Add(itemName);
                    Console.WriteLine("dir:   " + itemName);
                }
                else
                {
                    files.Add(itemName);
                    Console.WriteLine("file:  " + itemName);
                }
                anItem = reader.ReadLine();
            }

            reader.Close();
            response.Close();

            foreach (string fileToDelete in files)
            {
                request = (FtpWebRequest)WebRequest.Create(CombineURL(url, fileToDelete));
                request.Credentials = m_credentials;
                request.Method = WebRequestMethods.Ftp.DeleteFile;
                request.GetResponse().Close();
            }

            foreach (string directoryToDelete in directories)
            {
                // clear the dir
                ClearDirectory(CombineURL(url, directoryToDelete));
                // remove the empty dir
                request = (FtpWebRequest)WebRequest.Create(CombineURL(url, directoryToDelete));
                request.Credentials = m_credentials;
                request.Method = WebRequestMethods.Ftp.RemoveDirectory;
                request.GetResponse().Close();
            }
        }

        


    }


}
